package com.example.rabbitmq.example.springboot;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

@RestController
public class HelloController {

    private RabbitTemplate rabbitTemplate;

    @Autowired
    public void setTemplate(RabbitTemplate rabbitTemplate){
        this.rabbitTemplate = rabbitTemplate;
        this.rabbitTemplate.setConfirmCallback(((correlationData, flag, cause) -> {
            if(flag){
                try {
                    System.out.println("消息确认");
                }catch (Exception e){
                   e.printStackTrace();
                }
            }else {
                System.out.println(cause);
            }
        }));
    }

    @RequestMapping("/a")
    public String sendMessage(String message){
        MessageProperties properties = new MessageProperties();
        properties.setCorrelationId("1234");
        properties.setConsumerTag("msg1");
        properties.setHeader("x-delay", 1000);
        properties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN);
        properties.setContentEncoding(StandardCharsets.UTF_8.name());
        properties.setExpiration("1000");
        CorrelationData cd = new CorrelationData();
        cd.setId("msg");
        cd.setReturnedMessage(new Message("a".getBytes(StandardCharsets.UTF_8), null));
        Message ms = new Message(message.getBytes(StandardCharsets.UTF_8), properties);
        rabbitTemplate.convertAndSend("myex", "direct.ex", ms, cd);
        return "ok";
    }
}
